#!/bin/bash

# 为 Cursor HTTP 模式启动 MySQL MCP 服务器

# 获取脚本所在目录的绝对路径
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "=== 为 Cursor 启动 MySQL MCP HTTP 服务器 ==="
echo

# 检查配置文件
if [ ! -f "$PROJECT_ROOT/config/cursor-mcp-config.json" ]; then
    echo "❌ 未找到 cursor-mcp-config.json 配置文件"
    echo "请先运行: $PROJECT_ROOT/setup/setup_cursor_mcp.sh"
    exit 1
fi

# 从配置文件提取端口号
SERVER_PORT=$(grep -o '"url": "http://localhost:[0-9]*' "$PROJECT_ROOT/config/cursor-mcp-config.json" | grep -o '[0-9]*$')
if [ -z "$SERVER_PORT" ]; then
    SERVER_PORT=8080
    echo "⚠️  未能从配置文件获取端口，使用默认端口: $SERVER_PORT"
else
    echo "🔍 从配置文件读取端口: $SERVER_PORT"
fi

# 检查必需的环境变量
if [ -z "$MYSQL_USER" ] || [ -z "$MYSQL_DATABASE" ]; then
    echo
    echo "请设置数据库连接信息："
    
    if [ -z "$MYSQL_USER" ]; then
        read -p "MySQL 用户名: " MYSQL_USER
        export MYSQL_USER
    fi
    
    if [ -z "$MYSQL_DATABASE" ]; then
        read -p "数据库名: " MYSQL_DATABASE
        export MYSQL_DATABASE
    fi
    
    if [ -z "$MYSQL_PASSWORD" ]; then
        read -s -p "MySQL 密码: " MYSQL_PASSWORD
        echo
        export MYSQL_PASSWORD
    fi
fi

# 设置其他环境变量
export SERVER_PORT
export SERVER_HOST=${SERVER_HOST:-localhost}
export MYSQL_HOST=${MYSQL_HOST:-localhost}
export MYSQL_PORT=${MYSQL_PORT:-3306}

# 显示配置信息
echo
echo "=== 服务器配置 ==="
echo "HTTP 地址: http://$SERVER_HOST:$SERVER_PORT/mcp"
echo "健康检查: http://$SERVER_HOST:$SERVER_PORT/health"
echo "数据库: $MYSQL_HOST:$MYSQL_PORT/$MYSQL_DATABASE"
echo "用户: $MYSQL_USER"
echo

# 检查端口是否被占用
if lsof -Pi :$SERVER_PORT -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo "⚠️  端口 $SERVER_PORT 已被占用"
    echo "正在尝试停止现有服务..."
    pkill -f "mysql-mcp-server.*SERVER_PORT=$SERVER_PORT" || true
    sleep 2
fi

# 启动服务器
echo "🚀 启动 HTTP 服务器..."
echo "   请在 Cursor 中选择 'mysql-http' 配置"
echo "   按 Ctrl+C 停止服务器"
echo

# 启动服务器并保持前台运行
exec "$SCRIPT_DIR/start-http.sh" 